﻿using System;
using System.Web;
using System.Web.SessionState;

namespace Quintsys.Core.Services
{
    public static class SessionVariablesService
    {
        /// <summary>
        /// Gets the session.
        /// </summary>
        private static HttpSessionState Session
        {
            get
            {
                if (HttpContext.Current == null)
                    throw new ApplicationException("No Http Context, No Session to Get!");

                return HttpContext.Current.Session;
            }
        }

        /// <summary>
        /// Gets the specified key.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            if (Session[key] == null)
                return default(T);

            if (!typeof(T).IsEnum)
                return (T)Session[key];

            if (Enum.IsDefined(typeof(T), Session[key]))
                return (T)Enum.Parse(typeof(T), (string)Session[key], true);

            return default(T);
        }

        /// <summary>
        /// Sets the specified key.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        public static void Set<T>(string key, T value)
        {
            Session[key] = value;
        }

        /// <summary>
        /// Gets the string.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public static string GetString(string key)
        {
            var s = Get<string>(key);
            return s ?? string.Empty;
        }

        /// <summary>
        /// Sets the string.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        public static void SetString(string key, string value)
        {
            Set(key, value);
        }
    }
}